import cv2
from scripts.adaptive_binarizer import AdaptiveBinarizer
from scripts.functions import extract_text_from_crops, get_coordinates


def crop_and_ocr(
        image,
        model,
        confidence_threshold=0.75,
        iou_threshold=0.45,
        ocr_model_flag='tesseract'):
    coordinates = get_coordinates(
        image, model, confidence_threshold, iou_threshold)
    im = cv2.imread(image)
    binarizer = AdaptiveBinarizer()
    bin_im = binarizer.binarize(im)[..., ::-1]
    crops = []
    classes = []

    for _, row in coordinates.iterrows():
        x_min, y_min, x_max, y_max = map(
            int, row[['xmin', 'ymin', 'xmax', 'ymax']])
        crop = bin_im[y_min:y_max, x_min:x_max]
        crops.append(crop)
        classes.append(row['name'])
    text = extract_text_from_crops(crops, classes, ocr_model_flag)
    return text
